﻿using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Logistics;
using Nop.Core.Infrastructure;
using System;
using System.Web;
using System.Web.Mvc;

namespace Logistics.Web.Infrastructure
{
    public class LogisticsClosedAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null || filterContext.HttpContext == null)
                return;

            HttpRequestBase request = filterContext.HttpContext.Request;
            if (request == null)
                return;

            string actionName = filterContext.ActionDescriptor.ActionName;
            if (String.IsNullOrEmpty(actionName))
                return;

            string controllerName = filterContext.Controller.ToString();
            if (String.IsNullOrEmpty(controllerName))
                return;

            //don't apply filter to child methods
            if (filterContext.IsChildAction)
                return;

            if (!DataSettingsHelper.DatabaseIsInstalled())
                return;

            var logisticsInformationSettings = EngineContext.Current.Resolve<LogisticsInformationSettings>();
            if (!logisticsInformationSettings.Closed)
                return;

            if (EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.IsAdmin())
            {
                //do nothing - allow admin access
            }
            else
            {
                var storeClosedUrl = new UrlHelper(filterContext.RequestContext).RouteUrl("StoreClosed");
                filterContext.Result = new RedirectResult(storeClosedUrl);
            }
        }
    }
}